#pragma once
#include <iostream>
#include <cstdio>
#include <string>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/types.h>
#include <unistd.h>
using namespace std;

#define ERR_EXIT(m)         \
    do                      \
    {                       \
        perror(m);          \
        exit(EXIT_FAILURE); \
    } while (0)

class shm
{
public:
    shm(const string& username="user",const string &pathname=".", int projid=0x66,int gsize=4096) 
    : _gsize(gsize),
      _shmid(-1),
      _start_mem(nullptr),
      _username(username)
    {
        _key = ftok(pathname.c_str(), projid);
        if (_key < 0) ERR_EXIT("ftok\n");
        if(_username=="user") 
        {
            creatshmhelper(IPC_CREAT);
            attach();
        }
        else if(_username=="creater")
        {
            creatshmhelper(IPC_CREAT | IPC_EXCL | 0666);
            attach();
        }
        else{}
    }
    int getsize()
    {
        return _gsize;
    }
    void *get_start_mem()
    {
        printf("Virtual address:%p\n", _start_mem);
        return _start_mem;
    }
    ~shm()
    {
        if(_username=="creater") destroy();
    }
private:              // 这个地方不需要写出key，内为这个属于内核级别的。
    int _shmid;       // 共享内存id
    int _gsize;       // 共享内存大小
    void *_start_mem; // 其实虚拟地址
    string _username;
    int _key;
    void creatshmhelper(int flag)
    {
        _shmid = shmget(_key, _gsize, flag);
        if (_shmid < 0)
            ERR_EXIT("shmget");
        printf("shmid:%d\n", _shmid);
    }
    void attach()
    {
        _start_mem = shmat(_shmid, nullptr, 0);
        if ((long)_start_mem < 0)
            ERR_EXIT("attach");
        cout << "attach sucess" << endl;
    }
    void destroy()
    {
        if (_shmid == -1)
            return;
        int n = shmctl(_shmid, IPC_RMID, nullptr);
        if (n > 0)
            cout<<"shmctl delete" <<_shmid<<endl;
        else
            ERR_EXIT("shmctl\n");
    }
};